package com.fiveGroup.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fiveGroup.pojo.AdminUser;
import com.fiveGroup.pojo.vo.DataVo;
import com.fiveGroup.service.AdminUserService;
import com.fiveGroup.util.JwtUtil;
import com.fiveGroup.util.UserContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//管理员控制层
//管理员控制层
@RestController
@RequestMapping("/api/userinfo")
@Slf4j
@RequiredArgsConstructor
public class AdminUserController {

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    private JwtUtil jwtUtil;

    private final PasswordEncoder passwordEncoder;

    // 根据用户名获取当前登录的管理员信息
    private AdminUser getCurrentAdminUser() {
        try {
            String username = UserContextHolder.getUserName();
            if (username == null) {
                return null;
            }

            LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AdminUser::getUsername, username);
            return adminUserService.getOne(queryWrapper);
        } catch (Exception e) {
            log.error("获取当前管理员信息失败", e);
            return null;
        }
    }

    // 根据用户名泛查找-分页去获取所有管理员信息
    @GetMapping("/UserInfo")
    public DataVo getAdminUser(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "5") Integer pageSize,
                               @RequestParam(name = "username", required = false) String name) {
        IPage<AdminUser> adminUserIPage = new Page<>(page, pageSize);
        QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(name)) {
            queryWrapper.like("username", name);
        }
        adminUserService.page(adminUserIPage, queryWrapper);
        return DataVo.success(adminUserIPage);
    }

    // 新增管理员
    @PostMapping("/addUserInfo")
    public DataVo saveAdminUser(@RequestBody AdminUser adminUser) {
        AdminUser currentAdmin = getCurrentAdminUser();
        if (currentAdmin == null) {
            return DataVo.fail("用户未登录或不是管理员");
        }

        if (currentAdmin.getRoleId() != 1) {
            return DataVo.fail("权限不足，新增失败！(需要超级管理员)");
        }

        // 检查用户名是否已存在
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUser::getUsername, adminUser.getUsername());
        AdminUser existingUser = adminUserService.getOne(queryWrapper);
        if (existingUser != null) {
            return DataVo.fail("用户名已存在");
        }

        String encodedPassword = passwordEncoder.encode(adminUser.getPassword());
        adminUser.setPassword(encodedPassword);

        boolean saved = adminUserService.save(adminUser);
        return saved ? DataVo.success("新增管理员成功") : DataVo.fail("新增管理员失败");
    }

    //修改管理员（修改密码和用户名）
    @PostMapping("/updateUserInfo")
    public DataVo updateAdminUser(@RequestBody AdminUser adminUser) {
        if (StringUtils.hasText(adminUser.getPassword())) {
            String encodedPassword = passwordEncoder.encode(adminUser.getPassword());
            adminUser.setPassword(encodedPassword);
        }

        boolean updated = adminUserService.updateById(adminUser);
        return updated ? DataVo.success("修改成功") : DataVo.fail("修改失败");
    }

    // 删除单个管理员
    @PostMapping("/deleteUserInfo/{id}")
    public DataVo deleteAdminUser(@PathVariable Integer id) {
        AdminUser currentAdmin = getCurrentAdminUser();
        if (currentAdmin == null) {
            return DataVo.fail("用户未登录或不是管理员");
        }

        if (currentAdmin.getRoleId() != 1) {
            return DataVo.fail("权限不足，删除失败！(需要超级管理员)");
        }

        // 防止删除自己
        if (currentAdmin.getId().equals(Long.valueOf(id))) {
            return DataVo.fail("不能删除当前登录的账号");
        }

        boolean vs = adminUserService.removeById(id);
        return vs ? DataVo.success("删除成功") : DataVo.fail("删除失败");
    }

    //批量删除
    @PostMapping("/deleteAllUserInfo")
    public DataVo deleteAdminUsersAll(@RequestBody List<Integer> ids) {
        AdminUser currentAdmin = getCurrentAdminUser();
        if (currentAdmin == null) {
            return DataVo.fail("用户未登录或不是管理员");
        }

        if (currentAdmin.getRoleId() != 1) {
            return DataVo.fail("权限不足，删除失败！(需要超级管理员)");
        }

        // 防止删除自己
        if (ids.contains(currentAdmin.getId().intValue())) {
            return DataVo.fail("批量删除中包含了当前登录的账号，操作已取消");
        }

        boolean vs = adminUserService.removeByIds(ids);
        return vs ? DataVo.success("删除成功") : DataVo.fail("删除失败");
    }
}